package com.power.sifa.approve.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.plf.common.utils.StringUtil;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.approve.dao.Apl_archiveDao;
import com.power.sifa.approve.model.Apl_admreview;
import com.power.sifa.approve.model.Apl_archive;
import com.power.sifa.approve.model.Apl_main;
import com.power.sifa.approve.model.pageInfo.Apl_archivePageInfo;
import com.power.sifa.approve.service.Apl_admreviewService;
import com.power.sifa.approve.service.Apl_archiveService;
import com.power.sifa.approve.service.Apl_mainService;
import com.power.sifa.supervise.model.Apl_supervise;
import com.power.sifa.supervise.service.Apl_superviseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 归档记录业务层实现
 */
@Slf4j
@Service
public class Apl_archiveServiceImpl extends BaseServiceImpl implements Apl_archiveService {

//    @Resource
//    private Apl_archiveService service;

    @Autowired
    private Apl_archiveDao dao;

    @Autowired
    private Apl_mainService apl_mainService;

    @Autowired
    private Apl_admreviewService apl_admreviewService;

    @Autowired
    private Apl_superviseService apl_superviseService;


    @Override
    public Apl_archive getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    @Override
    public void saveOrUpdate(Apl_archive apl_archive) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_archive.getPrimaryKey() != null) {
            Apl_archive apl_archivefDb = dao.findById(apl_archive.getPrimaryKey()).orElse(null);
            if (apl_archivefDb != null) {
                BeanUtils.copyProperties(apl_archive, apl_archivefDb);
                dao.save(apl_archivefDb);
                return;
            }
        }
        dao.save(apl_archive);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_archive> findAll(Apl_archivePageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Apl_archive> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Apl_archive> list) {
        dao.saveAll(list);
    }

    /**
     * 通过appluid查询对应的归档记录
     *
     * @param applyid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Apl_archive getArchiveByApplyid(String applyid) {
        Apl_archive apl_archive = this.getById(applyid);
        if (ObjectUtil.isNotNull(apl_archive)) {
            return apl_archive;
        }
        return initialArchiveData(applyid);
    }

    /**
     * 通过appluid初始化归档记录
     *
     * @param applyid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Apl_archive initialArchiveData(String applyid) {
        Apl_main apl_main = apl_mainService.getById(applyid);
        Apl_admreview apl_admreview = apl_admreviewService.getById(applyid);
        if (ObjectUtil.isNotNull(apl_main) && ObjectUtil.isNotNull(apl_admreview)) {
            // 对对象的值进行赋值
            // 手动生成结束时间
            String closeTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            try {
                // 查询承办人
                String handlerId = "";
                String handledName = "";

                // 案件承办人 (第一立案审查人, 第二立案审查人), 先取审理的承办人值, 没有取受理的承办人值
                if (!StringUtil.isEmpty(apl_admreview.getHearfirstname())) {
                    handlerId = !StringUtil.isEmpty(apl_admreview.getHearsecondid()) ? apl_admreview.getHearfirstid() + "，" + apl_admreview.getHearsecondid()
                            : apl_admreview.getHearfirstid();
                    handledName = !StringUtil.isEmpty(apl_admreview.getHearsecondname()) ? apl_admreview.getHearfirstname() + "，" + apl_admreview.getHearsecondname()
                            : apl_admreview.getHearfirstname();
                } else if (!StringUtil.isEmpty(apl_admreview.getAcceptfirstname())) {
                    handlerId = !StringUtil.isEmpty(apl_admreview.getAcceptsecondid()) ? apl_admreview.getAcceptfirstid() + "，" + apl_admreview.getAcceptsecondid()
                            : apl_admreview.getAcceptfirstid();
                    handledName = !StringUtil.isEmpty(apl_admreview.getAcceptsecondname()) ? apl_admreview.getAcceptfirstname() + "，" + apl_admreview.getAcceptsecondname()
                            : apl_admreview.getAcceptfirstname();
                }


                Apl_archive apl_archive = Apl_archive.builder().id(applyid).code(apl_main.getAcceptcode()).applicantname(apl_admreview.getApplyname())
                        .targetname(apl_admreview.getTargetname()).thirdname(apl_admreview.getThirdname())
                        .checkperid(handlerId).checkper(handledName).acceptancedate(ObjectUtil.isNotNull(apl_main.getCreatetime()) && apl_main.getCreatetime().length() >= 10 ?
                                apl_main.getCreatetime().substring(0, 10) : apl_main.getCreatetime())
                        .closeingdate(ObjectUtil.isNotNull(apl_main.getFinishtime()) && apl_main.getFinishtime().length() >= 10 ?
                                apl_main.getFinishtime().substring(0, 10) : closeTime)
                        .caserecorddate(ObjectUtil.isNotNull(apl_main.getAccepttime()) && apl_main.getAccepttime().length() >= 10 ?
                                apl_main.getAccepttime().substring(0, 10) : apl_main.getAccepttime())
                        .paperpositivebook(0).paperpositivepage(0).paperreversebook(0)
                        .paperreversepage(0).paperotherbook(0).paperotherpage(0).elepositivebook(0).elepositivepage(0)
                        .elereversebook(0).elereversepage(0).eleotherbook(0).eleotherpage(0)
                        .build();
                this.saveOrUpdate(apl_archive);
                return apl_archive;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new Apl_archive();
        }
        return new Apl_archive();

    }

    @Override
    public Apl_archive initialSuperviseArchiveData(String applyid) {
        Apl_main apl_main = apl_mainService.getById(applyid);
        Apl_supervise apl_supervise = apl_superviseService.getById(applyid);
        if (ObjectUtil.isNotNull(apl_main) && ObjectUtil.isNotNull(apl_supervise)) {
            // 对对象的值进行赋值
            // 手动生成结束时间
            String closeTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            try {
                // 查询承办人
                String handlerId = "";
                String handledName = "";

                // 案件承办人 (第一立案审查人, 第二立案审查人), 先取审理的承办人值, 没有取受理的承办人值
                if (!StringUtil.isEmpty(apl_supervise.getFirstname())) {
                    handlerId = !StringUtil.isEmpty(apl_supervise.getSecondid()) ? apl_supervise.getFirstid() + "，" + apl_supervise.getSecondid()
                            : apl_supervise.getFirstid();
                    handledName = !StringUtil.isEmpty(apl_supervise.getSecondname()) ? apl_supervise.getFirstname() + "，" + apl_supervise.getSecondname()
                            : apl_supervise.getFirstname();
                }


                Apl_archive apl_archive = Apl_archive.builder().id(applyid).code(apl_main.getAcceptcode()).applicantname(apl_supervise.getApplyname())
                        .targetname(apl_supervise.getTargetname())
                        .checkperid(handlerId).checkper(handledName).acceptancedate(ObjectUtil.isNotNull(apl_main.getCreatetime()) && apl_main.getCreatetime().length() >= 10 ?
                                apl_main.getCreatetime().substring(0, 10) : apl_main.getCreatetime())
                        .closeingdate(ObjectUtil.isNotNull(apl_main.getFinishtime()) && apl_main.getFinishtime().length() >= 10 ?
                                apl_main.getFinishtime().substring(0, 10) : closeTime)
                        .caserecorddate(ObjectUtil.isNotNull(apl_main.getAccepttime()) && apl_main.getAccepttime().length() >= 10 ?
                                apl_main.getAccepttime().substring(0, 10) : apl_main.getAccepttime())
                        .paperpositivebook(0).paperpositivepage(0).paperreversebook(0)
                        .paperreversepage(0).paperotherbook(0).paperotherpage(0).elepositivebook(0).elepositivepage(0)
                        .elereversebook(0).elereversepage(0).eleotherbook(0).eleotherpage(0)
                        .build();
                this.saveOrUpdate(apl_archive);
                return apl_archive;
            } catch (Exception e) {
                log.error("初始化归档数据异常:{}", e.getMessage());
            }
            return new Apl_archive();
        }
        return new Apl_archive();
    }
}
